package com.test.qnews.volley;

/**
 * Created by dllo on 16/1/13.
 */
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import com.android.volley.toolbox.ImageLoader;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class DiskCache implements ImageLoader.ImageCache {

    static String cacheDir = "";

    //初始化写在构造方法里
    public DiskCache() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File root = Environment.getExternalStorageDirectory();
            //想存在自己建的文件夹
            File cacheFile = new File(root.getAbsolutePath() + "/cache");
            if (!cacheFile.exists()){
                cacheFile.mkdir();
            }
            cacheDir = cacheFile.getAbsolutePath();
        }
    }

    @Override
    public Bitmap getBitmap(String url) {
        if (url.contains(".jpg")) {
            url = url.substring(url.lastIndexOf("/"), url.lastIndexOf(".") + 4);//4是.jpg的长度
//        if (url.substring(url.length()-4,url.length()).equals(".jpg"))

            return BitmapFactory.decodeFile(cacheDir + "/" + url);
        }else{
            return null;
        }
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        if (url.contains(".jpg")) {
            url = url.substring(url.lastIndexOf("/"), url.lastIndexOf(".") + 4);
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(cacheDir + url);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (null != fos) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
